<template>
  <div class="box">
    <h1>{{ title }}</h1>
    <p>
      <a-input-search
        v-model:value="me"
        placeholder="输入用户名"
        @search="loginMe"
      >
        <template #enterButton>
          <a-button>登录</a-button>
        </template>
      </a-input-search>
    </p>
    <p>
      <a-input-search
        v-model:value="other"
        placeholder="输入用户名"
        @search="callOther"
      >
        <template #enterButton>
          <a-button>连接</a-button>
        </template>
      </a-input-search>
    </p>
    <p>
      <a-textarea
        readonly="readonly"
        v-model:value="msg"
        placeholder="消息框"
        :rows="4"
      />
    </p>
    <p>
      <a-input v-model:value="txt">
        <template #addonBefore>
          发送给:
          <a-select v-model:value="sender" :options="users" style="width: 80px">
          </a-select>
        </template>
        <template #addonAfter>
          <button @click="sendMsg">发送文本</button>
        </template>
      </a-input>
    </p>
  </div>
</template>

<script>
import { getCurrentInstance, ref, onMounted, onBeforeUnmount } from "vue";
import { message } from "ant-design-vue";
import MsgRTC from "./MyWebRTC/MsgRTC";
import _ from "lodash";

export default {
  name: "HelloWorld",
  props: {
    title: String,
  },
  setup() {
    const me = ref("");
    const other = ref("");
    const msg = ref("");
    const txt = ref(null);
    const sender = ref(null);
    const users = ref([]);

    const { proxy } = getCurrentInstance();

    let rtc = null;
    onMounted(() => {
      rtc = new MsgRTC(
        `${proxy.$wsUrl}`,
        // 消息传递回调
        (name, txt) => {
          // 建立通信的其它人加入集合
          if (name !== me.value) {
            const other = _.find(users.value, { label: name });
            if (!other) {
              users.value.push({ label: name, value: name });
            }
          }
          msg.value += `${name}:${txt}\n`;
        }
      );
    });

    onBeforeUnmount(() => {
      if (rtc) {
        rtc.dispose();
      }
    });

    // 用户登录
    const loginMe = () => {
      if (!me.value) {
        message.warn("请输入登录名");
        return;
      }
      // 发送登录信息给服务器
      rtc.join(me.value);
    };

    // 呼叫他人
    const callOther = () => {
      if (!other.value) {
        message.warn("请输入呼叫对象");
        return;
      }
      rtc.offer(other.value);
    };

    const sendMsg = () => {
      if (!sender.value) {
        message.warn("请选择发送对象");
        return;
      }
      if (!txt.value) {
        message.warn("请输入发送内容");
        return;
      }
      rtc.sendMsg(sender.value, txt.value);
      txt.value = null;
    };

    return { me, other, msg, txt, users, sender, loginMe, callOther, sendMsg };
  },
};
</script>

<style lang="less" scoped>
.box {
  width: 500px;
  margin-left: auto;
  margin-right: auto;
}
</style>
